
import axios from 'axios'
import session from '@/utils/SessionStorageUtil'
import { isBlob } from '@/utils/ValidateUtil'
import { message } from '@/utils/ResetMessage'
import router from '@/router'
// 创建 axios 实例
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    const token = session.GET('test_token')
    if (token) {
      config.headers['Token'] = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    if (handleApiResponseStatus(response)) return response.data
  },
  error => {
    // 错误处理
    if (handleHttpResponseStatus(error)) return Promise.reject(error)
    console.error('Error:', error)
    return Promise.reject(error)
  }
)

// 封装 get 方法
export function GET (url, params) {
  return new Promise((resolve, reject) => {
    instance.get(url, { params: params }).then(response => {
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}

// 封装 post 方法
export function POST (url, data) {
  return new Promise((resolve, reject) => {
    instance.post(url, data).then(response => {
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}
//
// 封装文件下载方法
export function DOWNLOAD (url, data, fileName = '模板', suffix = 'xlsx') {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Token': `Bearer ${session.GET('test_token')}`
      },
      responseType: 'blob',
      data
    }).then(response => {
      let blob = null
      if (isBlob(response.data)) {
        blob = response.data
      } else {
        blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
      }
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, `${fileName}.${suffix}`)
      } else {
        let link = document.createElement('a')
        let href = window.URL.createObjectURL(blob)
        link.href = href
        link.download = `${fileName}.${suffix}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(href)
        resolve()
      }
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}

// 封装文件上传方法
export function UPLOAD (url, formData) {
  return new Promise((resolve, reject) => {
    instance.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: progressEvent => {
        // 处理上传进度
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        console.log(`Upload Progress: ${percentCompleted}%`)
      }
    }).then(response => {
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}

const handleApiResponseStatus = response => {
  const code = response.data && response.data.code
  if (code === 0 || code === 200) {
    return true
  } else if (code === 200001) {
    message({
      message: '登录过期，请重新登录( 3 秒后自动跳转登录)',
      type: 'error',
      onClose: () => {
        session.DEL('test_token')
        setTimeout(() => {
          router.push({ name: 'login' })
        }, 3000)
      }
    })
  } else {
    message({ message: response.data.msg || response.data.message, type: 'error' })
    return false
  }
}

const handleHttpResponseStatus = error => {
  message({ message: '网络异常', type: 'error' })
  session.DEL('test_token')
  console.log(error)
  return false
}
